﻿Imports System.IO

Public Class Buscar
    Dim tabla As DataTable
    Dim dtFiltro As DataTable
    Dim cerrar As Boolean = False
    Dim sComp As Object

    Dim filtrado As Boolean = False

    Dim vColumnas As Collection

    'Dim regreso As String

    Public Structure Comparativa
        Dim Costo As String
        Dim Precio As String
        Dim Nombre As String
        Dim Cliente As String
        Dim Tipo_Iva As String
    End Structure

    Public Structure Resultado
        Dim id As String
        Dim cantidad As Double
    End Structure

    Dim cResultado As Collection

    Dim vUnico As Boolean

    Dim nums As Number_Input = New Number_Input()

    Public Function Mostrar(ByVal col As Color, ByVal pImg As Boolean, ByVal dt As DataTable, ByVal columnas As Collection, Optional ByVal Valor_Unico As Boolean = True, Optional ByVal Comp As Object = Nothing) As Collection
        Me.Cursor = Cursors.WaitCursor

        'dgDatos = New DataGridView


        vUnico = Valor_Unico

        Me.BackColor = col
        dgFiltro.BackgroundColor = col
        dgDatos.BackgroundColor = col
        dgDatos.DefaultCellStyle.SelectionBackColor = col
        dgDatos.DefaultCellStyle.SelectionForeColor = Color.Black
        dgFiltro.DefaultCellStyle.SelectionBackColor = col
        dgFiltro.DefaultCellStyle.SelectionForeColor = Color.Black
        pImagen.Visible = pImg

        tabla = New DataTable
        tabla = dt


        If Not vUnico Then
            tabla.Columns.Add("X", GetType(Boolean))
            tabla.Columns.Add("#", GetType(Double))

            tabla.Columns("#").DefaultValue = 0

            tabla.Columns("X").SetOrdinal(0)
            tabla.Columns("#").SetOrdinal(1)

            tabla.Columns("X").DefaultValue = False

            'For Each fila As DataRow In tabla.Rows
            '    fila("X") = False
            '    'fila("#") = 0
            'Next

            'tabla.Columns("X").AllowDBNull = False
        End If


        vColumnas = columnas

        dgDatos.DataSource = tabla

        dgDatos.Columns(0).DefaultCellStyle.NullValue = False



        filtrado = False

        sComp = Comp

        dtFiltro = New DataTable("FILTRO")
        dtFiltro.Columns.Add("Columna")
        dtFiltro.Columns.Add("Filtro")

        Dim i As Integer = 0
        For Each columna As DataGridViewColumn In dgDatos.Columns
            If vColumnas.Contains(columna.HeaderText) Then
                Dim fila As DataRow = dtFiltro.NewRow
                fila(0) = columna.HeaderText

                If i = 1 Then
                    dtFiltro.Rows.InsertAt(fila, 0)
                Else
                    dtFiltro.Rows.Add(fila)
                End If

                i += 1
            End If
        Next

        If Not vUnico Then
            columnas.Add("X", "X")
            columnas.Add("#", "#")
        End If


        cResultado = New Collection()


        Oculta_Columnas()


        dgFiltro.DataSource = dtFiltro

        Me.Cursor = Cursors.Default

        cerrar = False

        Me.Refresh()

        Me.ShowDialog()

        If tabla.Columns.Contains("X") Then
            tabla.Columns.Remove("X")
            columnas.Remove("X")
        End If

        If tabla.Columns.Contains("#") Then
            tabla.Columns.Remove("#")
            columnas.Remove("#")
        End If

        Return cResultado
    End Function

    Private Sub Oculta_Columnas()
        For Each columna As DataGridViewColumn In dgDatos.Columns
            columna.Visible = False
            If vColumnas.Contains(columna.HeaderText) Then columna.Visible = True
        Next
    End Sub

    Private Sub dgFiltro_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles dgFiltro.KeyUp
        If e.KeyCode = Keys.Right Then
            dgDatos.Focus()
            If dgDatos.Rows.Count > 0 Then
                dgDatos.Rows(0).Selected = True
            End If
            dgFiltro.SelectedCells(0).Selected = False
            Exit Sub
        End If
        Filtrar()
    End Sub

    Private Sub dgFiltro_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles dgFiltro.SelectionChanged
        If dgFiltro.Columns.Count > 1 Then
            If dgFiltro.SelectedCells.Count > 0 Then
                If dgFiltro.SelectedCells.Item(0).ColumnIndex = 0 Then
                    Dim fila As Integer = dgFiltro.SelectedCells.Item(0).RowIndex
                    dgFiltro.Rows(fila).Cells(1).Selected = True
                End If
            End If
        End If
    End Sub

    Private Sub Filtrar()
        Dim filtro As String = ""
        For Each fila As DataGridViewRow In dgFiltro.Rows
            If fila.Cells(1).Value.ToString.Trim.Length > 0 Then
                filtro += fila.Cells(0).Value & " like '%" & fila.Cells(1).Value.ToString & "%' and "
            End If
        Next

        If filtro.Trim.Length > 0 Then
            If filtro.EndsWith("and ") Then filtro = filtro.Substring(0, filtro.Length - 4)
            Dim tabla2 As New DataTable
            tabla2 = tabla.Clone
            For Each fila As DataRow In tabla.Select(filtro)
                tabla2.ImportRow(fila)
            Next

            dgDatos.DataSource = Nothing
            dgDatos.Columns.Clear()
            dgDatos.Rows.Clear()

            filtrado = True

            If (Not sComp Is Nothing) AndAlso (Not CType(sComp, Comparativa).Cliente Is Nothing) Then
                tabla2.Columns.Add(CType(sComp, Comparativa).Nombre, GetType(Image))
                tabla2.Columns.Add("PRECIO", GetType(Double))
                tabla2.Columns.Add("UTIL", GetType(Double))
                tabla2.Columns.Add("COSTO", GetType(Double))

                For Each fila As DataRow In tabla2.Rows
                    Dim col As Integer = 0

                    If vUnico = False Then col = 2

                    Dim politicas As DataRow() = dsInfo.Tables("POLITICAS").Select("CLIE='" & CType(sComp, Comparativa).Cliente & "' and CLV_INI<=" & Val(fila(col)) & " and CLV_FIN>=" & Val(fila(col)))
                    Dim precio As Integer = 1
                    If politicas.Length > 0 Then
                        precio = Val(politicas(0)("LISTA_PREC"))
                    End If
                    Dim cPrecio As String = "PRECIO" & precio.ToString
                    Dim iva As Double = CType(dsInfo.Tables("IMPUESTOS").Select("CVEESQIMPU=" & fila(CType(sComp, Comparativa).Tipo_Iva))(0), DataRow)("IMPUESTO4") / 100
                    fila("PRECIO") = fila(cPrecio) + (fila(cPrecio) * iva)
                    Dim utilidad As Double = Val(fila(cPrecio)) - Val(fila(CType(sComp, Comparativa).Costo))
                    fila("UTIL") = utilidad
                    fila("COSTO") = fila(CType(sComp, Comparativa).Costo)
                Next


                If tabla2.Rows.Count > 0 Then
                    Dim minUtil As Double = tabla2.Compute("MIN(UTIL)", "COSTO>0")
                    Dim maxUtil As Double = tabla2.Compute("MAX(UTIL)", "COSTO>0") - minUtil

                    Dim eColor As New Bitmap(ruta_programa & "\Images\color.png")
                    Dim eBlanco As New Bitmap(ruta_programa & "\Images\blanco.png")

                    Dim ancho As Integer = 60
                    Dim alto As Integer = 14

                    Comprime_Imagen(eColor, ancho, alto)
                    Comprime_Imagen(eBlanco, ancho, alto)

                    Dim col As Integer = 0
                    If vUnico = False Then col = 2

                    tabla2.Columns(CType(sComp, Comparativa).Nombre).SetOrdinal(col + 2)
                    tabla2.Columns("UTIL").SetOrdinal(col + 3)
                    tabla2.Columns("PRECIO").SetOrdinal(col + 4)

                    For Each fila As DataRow In tabla2.Rows
                        If fila("COSTO") > 0 Then
                            Dim porc As Integer = 0

                            If maxUtil > 0 Then
                                porc = ((fila("UTIL") - minUtil) / maxUtil) * 10
                            End If


                            Dim final As Integer = ancho * (Int(porc / 2) * 2 / 10)

                            Dim bmp As New Bitmap(ancho, alto)
                            Dim g As Graphics = Graphics.FromImage(bmp)

                            g.DrawImage(eColor, New Rectangle(0, 0, ancho, alto))
                            g.FillRectangle(Brushes.Magenta, New RectangleF(final + 1, 0, ancho - final, alto))
                            bmp.MakeTransparent(Color.Magenta)
                            bmp.MakeTransparent(Color.White)
                            'bmp.MakeTransparent(Color.Magenta)

                            Dim bmp2 As New Bitmap(ancho, alto)
                            Dim g2 As Graphics = Graphics.FromImage(bmp2)
                            g2.DrawImage(eBlanco, New Rectangle(0, 0, ancho, alto))
                            g2.DrawImage(bmp, New Rectangle(0, 0, ancho, alto))

                            fila(CType(sComp, Comparativa).Nombre) = New Bitmap(bmp2)
                        Else
                            fila(CType(sComp, Comparativa).Nombre) = New Bitmap(eBlanco)
                        End If
                    Next
                End If

                dgDatos.DataSource = tabla2

                Oculta_Columnas()

                dgDatos.Columns("PRECIO").DefaultCellStyle.Format = "$ ###,###,##0.00"
                dgDatos.Columns("UTIL").DefaultCellStyle.Format = "$ ###,###,##0.00"
                dgDatos.Columns("COSTO").DefaultCellStyle.Format = "$ ###,###,##0.00"
                dgDatos.Columns("PRECIO").Visible = True
                dgDatos.Columns("UTIL").Visible = False
                dgDatos.Columns("COSTO").Visible = False
                dgDatos.Columns(CType(sComp, Comparativa).Nombre).Visible = True
            Else
                dgDatos.DataSource = tabla2

                Oculta_Columnas()
            End If

        Else
            filtrado = False
            dgDatos.DataSource = tabla

            Oculta_Columnas()
        End If


        If dgDatos.SelectedCells.Count > 0 Then dgDatos.SelectedCells(0).Selected = False
    End Sub

    Private Sub Buscar_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        If cerrar = False Then
            cResultado = New Collection
        End If
    End Sub

    Private Sub Buscar_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
        If e.KeyCode = Keys.Escape Then
            cResultado = New Collection
            cerrar = True
            Me.Close()
        End If
    End Sub

    Private Sub Buscar_Shown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Shown
        If dgDatos.SelectedCells.Count > 0 Then dgDatos.SelectedCells(0).Selected = False
        'dgFiltro.SelectedCells(0).Selected = False
        'dgFiltro.Rows(1).Cells(1).Selected = True
        dgFiltro.Focus()
        pbImagen.Image = Nothing
    End Sub

    Private Sub dgDatos_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles dgDatos.DoubleClick
        If dgDatos.SelectedCells.Count > 0 AndAlso vUnico Then
            Regresa_Valor()
        End If
    End Sub

    Private Sub dgDatos_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles dgDatos.KeyDown
        If vUnico = False And e.KeyCode = Keys.X Then
            For Each fila As DataGridViewRow In dgDatos.SelectedRows

                If fila.Cells("X").Value Is DBNull.Value OrElse fila.Cells("X").Value = False Then
                    fila.Cells("X").Value = True
                    fila.Cells("#").Value = nums.Mostrar(, True, "Escribe la cantidad")
                Else
                    fila.Cells("X").Value = False
                    fila.Cells("#").Value = 0
                End If
            Next
        End If

        If e.KeyCode = Keys.Space Then
            Regresa_Valor()
        End If
    End Sub

    Private Sub Regresa_Valor()
        If dgDatos.SelectedRows.Count <= 0 Then
            msg.Mostrar("No hay nada seleccionado", "", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End If

        If vUnico Then
            Dim res As Resultado = New Resultado()
            res.id = dgDatos.SelectedRows(0).Cells(0).Value
            res.cantidad = 0

            cResultado.Add(res, res.id)

            cerrar = True
            Me.Close()
        Else
            'dgDatos.Sort(dgDatos.Columns("X"), System.ComponentModel.ListSortDirection.Descending)

            'dgDatos.Refresh()

            'If Not dgDatos.SortedColumn Is dgDatos.Columns("X") Then dgDatos.Sort(dgDatos.Columns("X"), System.ComponentModel.ListSortDirection.Descending)

            For Each fila As DataGridViewRow In dgDatos.Rows
                'If fila.Cells("X").Value Is DBNull.Value OrElse fila.Cells("X").Value = False Then Exit For
                If Not (fila.Cells("X").Value Is DBNull.Value OrElse fila.Cells("X").Value = False) Then
                    Dim res As Resultado = New Resultado()
                    res.id = fila.Cells(2).Value
                    res.cantidad = fila.Cells(1).Value

                    cResultado.Add(res, res.id)
                End If
            Next

            'dgDatos.Refresh()



            'dgDatos.EndEdit()

            'Dim dtTemp As DataTable = 

            'For Each fila As DataRow In dgDatos.DataSource.Select("Cant>0")
            '    Dim res As Resultado = New Resultado()
            '    res.id = fila(2)
            '    res.cantidad = fila(1)

            '    cResultado.Add(res, res.id)
            'Next

            tabla.Columns.Remove("X")
            tabla.Columns.Remove("#")

            'If tabla.Columns.Contains("X") Then
            '    tabla.Columns.Remove("X")
            '    columnas.Remove("X")
            'End If

            'If tabla.Columns.Contains("#") Then
            '    tabla.Columns.Remove("#")
            '    columnas.Remove("#")
            'End If


            cerrar = True
            Me.Close()

        End If
    End Sub

    Private Sub dgDatos_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles dgDatos.KeyUp
        If e.KeyCode = Keys.Left Then
            dgFiltro.Focus()
            If dgFiltro.Rows.Count > 0 Then
                dgFiltro.Rows(0).Selected = True
            End If
            dgDatos.SelectedCells(0).Selected = False
            Exit Sub
        End If
    End Sub

    Private Sub dgDatos_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles dgDatos.SelectionChanged
        If dgDatos.SelectedCells.Count > 0 Then

            Dim col As Integer = 0

            If Not vUnico Then col = 2

            lbSeleccion.Text = dgDatos.Columns(col).HeaderText & " - " & dgDatos.SelectedRows(0).Cells(col).Value
            lbSeleccion.Image = Nothing


            If Not sComp Is Nothing AndAlso filtrado = True AndAlso dgDatos.Focused = True AndAlso dgDatos.Columns.Contains(CType(sComp, Comparativa).Nombre) Then
                lbSeleccion.Image = CType(dgDatos.DataSource, DataTable).Rows(dgDatos.SelectedRows(0).Index)(CType(sComp, Comparativa).Nombre)
            End If

            If pImagen.Visible AndAlso (Not dgDatos.SelectedRows(0).Cells(col).Value Is DBNull.Value) Then pbImagen.Image = Carga_Imagen(dgDatos.SelectedRows(0).Cells(col).Value)
        Else
            lbSeleccion.Text = ""
        End If
    End Sub

    Private Sub pbImagen_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles pbImagen.DoubleClick
        If msg.Mostrar("Desea cambiar la imagen de este producto?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = "&Si" Then
            Dim op As New OpenFileDialog

            op.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.MyPictures)
            op.Filter = "PNG files (*.png)|*.png|JPEG files (*.jpg)|*.jpg|Todos los archivos (*.*)|*.*"
            op.FilterIndex = 1
            op.RestoreDirectory = True

            If op.ShowDialog() = System.Windows.Forms.DialogResult.OK Then

                Try
                    Dim archivo As String = op.FileName
                    Dim extension As String = archivo.Split(".").GetValue(1).ToString

                    Dim imagen1 As String = ruta_programa & "\Fotos\" & dgDatos.SelectedRows(0).Cells(0).Value & ".png"
                    Dim imagen2 As String = ruta_programa & "\Fotos\" & dgDatos.SelectedRows(0).Cells(0).Value & ".jpg"

                    If File.Exists(imagen1) Then File.Delete(imagen1)
                    If File.Exists(imagen2) Then File.Delete(imagen2)

                    File.Copy(archivo, ruta_programa & "\Fotos\" & dgDatos.SelectedRows(0).Cells(0).Value & "." & extension)

                    pbImagen.Image = Carga_Imagen(dgDatos.SelectedRows(0).Cells(0).Value)
                Catch Ex As Exception
                    msg.Mostrar("Ocurrio un error al cargar la imagen", "", MessageBoxButtons.OK, MessageBoxIcon.Error)
                End Try
            End If
        End If

    End Sub

    Private Sub dgDatos_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgDatos.CellContentClick
        If dgDatos.SelectedRows.Count > 0 AndAlso vUnico = False AndAlso e.ColumnIndex = 0 Then
            If dgDatos.SelectedRows(0).Cells("X").Value Is DBNull.Value OrElse dgDatos.SelectedRows(0).Cells("X").Value = False Then
                dgDatos.SelectedRows(0).Cells("X").Value = True
                'tabla.Rows(e.RowIndex)(0) = True
                dgDatos.SelectedRows(0).Cells("#").Value = nums.Mostrar(, True, "Escribe la cantidad")
                'tabla.Rows(e.RowIndex)(1) = dgDatos.SelectedRows(0).Cells("#").Value
            Else
                dgDatos.SelectedRows(0).Cells("X").Value = False
                'tabla.Rows(e.RowIndex)(0) = False
                dgDatos.SelectedRows(0).Cells("#").Value = 0
                'tabla.Rows(e.RowIndex)(1) = 0
            End If
        End If
    End Sub
End Class